package com.newdjk.newdoctor.ui;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;

import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.google.gson.Gson;
import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.dialog.CityChooseDialog;
import com.newdjk.newdoctor.entity.QueryOrgInfoEntity;
import com.newdjk.newdoctor.entity.UPloadOrgInfoEntity;
import com.newdjk.newdoctor.entity.UploadImageEntity;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Base64Util;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.DisplayUtil;
import com.newdjk.newdoctor.utils.StrUtil;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.view.MultiImageUploadView;
import com.newdjk.newdoctor.view.RoundImageUploadView;
import com.newdjk.okhttp.entity.BaseEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 重置密码
 */
public class BaseInfoActivity extends BasActivity {


    @BindView(R.id.logo_view)
    RoundImageUploadView logoView;
    @BindView(R.id.lv_logo)
    LinearLayout lvLogo;
    @BindView(R.id.banner_view)
    RoundImageUploadView bannerView;
    @BindView(R.id.lv_yiliao_xukezheng)
    LinearLayout lvYiliaoXukezheng;
    @BindView(R.id.lv_result)
    LinearLayout lvResult;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_name)
    EditText tvName;
    @BindView(R.id.tv_area_title)
    TextView tvAreaTitle;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_mobile)
    EditText tvMobile;
    @BindView(R.id.tv_yingye_time)
    EditText tvYingyeTime;
    @BindView(R.id.tv_jianjie)
    EditText tvJianjie;
    @BindView(R.id.lv_yaodian_xukezheng)
    LinearLayout lvYaodianXukezheng;
    @BindView(R.id.jianjie_view)
    RoundImageUploadView jianjieView;
    @BindView(R.id.btn_submit)
    AppCompatButton btnSubmit;
    @BindView(R.id.tv_title_jianjie)
    TextView tvTitleJianjie;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    private int reletype;
    private List<String> mBannerPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private List<String> mLogoPicList = new ArrayList<>(); //上传的图片凭证的数据源
    private List<String> mJianjiePicList = new ArrayList<>(); //上传的图片凭证的数据源
    private final int IMAGE_REQUEST_lOGO_CODE = 1;
    private final int IMAGE_REQUEST_BANNER_CODE = 2;
    private final int IMAGE_REQUEST_Jianjie_CODE = 3;
    private String TAG = "BaseInfoActivity";
    private QueryOrgInfoEntity queryOrgInfoEntity;
    private Gson mGson = new Gson();
    private String mProvinceName;
    private String mProvinceID;
    private String mcityName;
    private String mcityID;
    private String mAreaid;
    private String mAreaName;
    private String provinceID = "0";
    private String currentarea;

    @Override
    protected String setTitle() {
        return "基本信息";
    }

    @Override
    protected int initViewResId() {
        return R.layout.activity_baseinfo;
    }


    @Override
    protected void initListener() {
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (logoView.getFiles().size() == 0) {
                    ToastUtil.setToast("请上传logo图片");
                    return;
                }
                if (bannerView.getFiles().size() == 0) {
                    ToastUtil.setToast("请上传banner图片");
                    return;
                }
                if (TextUtils.isEmpty(tvName.getText().toString())) {
                    if (reletype == 1 || reletype == 2 || reletype == 3) {
                        ToastUtil.setToast("诊所名称不能为空");
                    } else {
                        ToastUtil.setToast("药店名称不能为空");
                    }

                    return;
                }
                if (TextUtils.isEmpty(tvLocation.getText().toString())) {

                    if (reletype == 1 || reletype == 2 || reletype == 3) {
                        ToastUtil.setToast("诊所区域不能为空");
                    } else {
                        ToastUtil.setToast("药店区域不能为空");
                    }
                    return;
                }


                if (TextUtils.isEmpty(tvMobile.getText().toString())) {
                    ToastUtil.setToast("手机号码不能为空");
                    return;
                }

                if (!StrUtil.isMobile(StrUtil.getString(tvMobile))) {
                    ToastUtil.setToast(getResources().getString(R.string.mobile_empty));
                    return;
                }
                if (TextUtils.isEmpty(tvYingyeTime.getText().toString())) {
                    ToastUtil.setToast("营业时间不能为空");
                    return;
                }

                if (TextUtils.isEmpty(tvJianjie.getText().toString())) {
                    if (reletype == 1 || reletype == 2 || reletype == 3) {
                        ToastUtil.setToast("诊所简介不能为空");
                    } else {
                        ToastUtil.setToast("药店简介不能为空");
                    }

                    return;
                }
//                if (jianjieView.getFiles().size() == 0) {
//                    ToastUtil.setToast("请上传简介图片");
//                    return;
//                }

                UPloadOrgInfoEntity uPloadOrgInfoEntity = new UPloadOrgInfoEntity();

                uPloadOrgInfoEntity.setOrgId(queryOrgInfoEntity.getOrgId());
                if (mLogoPicList.size() > 0) {
                    uPloadOrgInfoEntity.setPicturePath(mLogoPicList.get(0));
                } else {
                    uPloadOrgInfoEntity.setPicturePath(queryOrgInfoEntity.getPicturePath());
                }

                uPloadOrgInfoEntity.setOrgDes(tvJianjie.getText().toString());
                uPloadOrgInfoEntity.setServiceTime(tvYingyeTime.getText().toString());


                if (mBannerPicList.size() > 0) {
                    List<UPloadOrgInfoEntity.OrgImgsBean> OrgImgsBeanPicList = new ArrayList<>();
                    for (int i = mBannerPicList.size()-1; i >=0; i--) {
                        UPloadOrgInfoEntity.OrgImgsBean orgImgsBean = new UPloadOrgInfoEntity.OrgImgsBean();
                        orgImgsBean.setImgPath(mBannerPicList.get(i));
                        OrgImgsBeanPicList.add(orgImgsBean);
                    }
                    uPloadOrgInfoEntity.setOrgImgs(OrgImgsBeanPicList);
                } else {
                    List<UPloadOrgInfoEntity.OrgImgsBean> OrgImgsBeanPicList = new ArrayList<>();
                    for (int i = 0; i < queryOrgInfoEntity.getOrgImgs().size(); i++) {
                        UPloadOrgInfoEntity.OrgImgsBean orgImgsBean = new UPloadOrgInfoEntity.OrgImgsBean();
                        orgImgsBean.setImgPath(orgImgsBean.getImgPath());
                        OrgImgsBeanPicList.add(orgImgsBean);
                    }
                    uPloadOrgInfoEntity.setOrgImgs(OrgImgsBeanPicList);
                }


                uPloadOrgInfoEntity.setContact(tvMobile.getText().toString());
//                if (mJianjiePicList.size() > 0) {
//                    uPloadOrgInfoEntity.setOrgDesImg(mJianjiePicList.get(0));
//                } else {
//                    uPloadOrgInfoEntity.setOrgDesImg(queryOrgInfoEntity.getOrgDesImg());
//                }

                uPloadOrgInfoEntity.setOrgName(tvName.getText().toString());
                uPloadOrgInfoEntity.setOrdAddress(tvLocation.getText().toString());

                String json = mGson.toJson(uPloadOrgInfoEntity);

                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

                NetServices.Factory.getService().SaveOrg(
                        body
                ).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseComPleteObserver(BaseInfoActivity.this) {
                            @Override
                            protected void onSuccees(BaseEntity t) throws Exception {
                                ToastUtil.setToast("提交成功");
                                finish();
                                return;

                            }

                            @Override
                            protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                                super.onFailure(e, erroressage, isNetWorkError);
                                ToastUtil.setToast("" + erroressage);
                            }
                        });
            }
        });


    }

    @Override
    protected void onRightTvClick(View v) {
        super.onRightTvClick(v);
        Intent yifei = new Intent(BaseInfoActivity.this, WebViewActivity.class);
        yifei.putExtra(Contants.TYPE, 25);
        yifei.putExtra("clinid", MyApplication.LoginEntity.getUser().getOrgId().get(0));
        startActivity(yifei);
    }

    @Override
    protected void initData() {
        QueryOrgAndImgByDrId();
    }

    private void QueryOrgAndImgByDrId() {
        NetServices.Factory.getService().QueryOrgAndImgByDrId(MyApplication.LoginEntity.getUser().getDoctorId()).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<QueryOrgInfoEntity>() {
                    @Override
                    protected void onFailure(Throwable e, String erroressage, boolean isNetWorkError) throws Exception {
                        super.onFailure(e, erroressage, isNetWorkError);
                    }

                    @Override
                    protected void onSuccees(BaseEntity<QueryOrgInfoEntity> t) throws Exception {
                        queryOrgInfoEntity = t.getData();
                        tvLocation.setText(TextUtils.isEmpty(queryOrgInfoEntity.getOrdAddress()) ? "" : queryOrgInfoEntity.getOrdAddress());
                        tvMobile.setText(TextUtils.isEmpty(queryOrgInfoEntity.getContact()) ? "" : queryOrgInfoEntity.getContact());
                        tvName.setText(TextUtils.isEmpty(queryOrgInfoEntity.getOrgName()) ? "" : queryOrgInfoEntity.getOrgName());
                        tvYingyeTime.setText(TextUtils.isEmpty(queryOrgInfoEntity.getServiceTime()) ? "" : queryOrgInfoEntity.getServiceTime());
                        tvJianjie.setText(TextUtils.isEmpty(queryOrgInfoEntity.getOrgDes()) ? "" : queryOrgInfoEntity.getOrgDes());
                        if (!TextUtils.isEmpty(queryOrgInfoEntity.getPicturePath())){
                            logoView.addFile(new File(queryOrgInfoEntity.getPicturePath()));
                        }

                        for (QueryOrgInfoEntity.OrgImgsBean s1 : queryOrgInfoEntity.getOrgImgs()) {
                            bannerView.addFile(new File(s1.getImgPath()));
                            mBannerPicList.add(s1.getImgPath());
                        }
//                        if (!TextUtils.isEmpty(queryOrgInfoEntity.getOrgDesImg())){
//                            jianjieView.addFile(new File(queryOrgInfoEntity.getOrgDesImg()));
//                        }

                    }
                });
    }


    @Override
    protected void initView() {
        setRightText("预览");
        if (MyApplication.DoctorInfoEntity != null) {
            reletype = MyApplication.DoctorInfoEntity.getRoleType();
        }

        if (reletype == 1 || reletype == 2 || reletype == 3) {
            tvTitle.setText("诊所名称");
            tvAreaTitle.setText("诊所区域");
            tvTitleJianjie.setText("诊所简介");
            tvInfo.setText("诊所信息");
        } else {
            tvTitle.setText("药店名称");
            tvAreaTitle.setText("药店区域");
            tvTitleJianjie.setText("药店简介");
            tvInfo.setText("药店信息");
        }


        setUpLogoView();
        setUpBannerView();
        setUpJianjieView();
    }

    private void setUpJianjieView() {
        jianjieView.setAddHandlerImage(R.drawable.image_add);
        jianjieView.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return 200;
            }

            @Override
            public int getHeight() {
                return 200;
            }
        });
        jianjieView.setMax(1);
        jianjieView.setNumCol(4);
        jianjieView.setImgMargin(DisplayUtil.dp2px(this, 10));
        jianjieView.setCloseHandlerImage(R.drawable.ic_delete_photo);
        jianjieView.setOnItemClickListener(new MultiImageUploadView.OnItemClickListener() {
            @Override
            public void onItemClick(MultiImageUploadView parent, int position) {
                Log.d(TAG,parent.getFiles().get(position).getPath()+""+position);
                ArrayList<String> list=new ArrayList<>();
                list.add(parent.getFiles().get(position).getPath());
                Intent intent = new Intent(BaseInfoActivity.this, PictureViewerActivity.class);
                intent.putExtra("pic_all", list);
                intent.putExtra("pic_position",position);
                startActivity(intent);
            }
        });
        jianjieView.setPadding(0, 0, 0, 0);
        jianjieView.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage(jianjieView, IMAGE_REQUEST_Jianjie_CODE);
            }
        });

        jianjieView.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                if (mJianjiePicList.size() > 0) {
                    mJianjiePicList.remove(pos);
                }

            }
        });
    }

    private void setUpBannerView() {
        bannerView.setAddHandlerImage(R.drawable.image_add);
        bannerView.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return 200;
            }

            @Override
            public int getHeight() {
                return 200;
            }
        });
        bannerView.setMax(6);
        bannerView.setNumCol(4);
        bannerView.setImgMargin(DisplayUtil.dp2px(this, 10));
        bannerView.setCloseHandlerImage(R.drawable.ic_delete_photo);
        bannerView.setOnItemClickListener(new MultiImageUploadView.OnItemClickListener() {
            @Override
            public void onItemClick(MultiImageUploadView parent, int position) {
                Log.d(TAG,parent.getFiles().get(position).getPath()+""+position);
                ArrayList<String> list=new ArrayList<>();
                list.add(parent.getFiles().get(position).getPath());
                Intent intent = new Intent(BaseInfoActivity.this, PictureViewerActivity.class);
                intent.putExtra("pic_all", list);
                intent.putExtra("pic_position",position);
                startActivity(intent);
            }
        });
        bannerView.setPadding(0, 0, 0, 0);
        bannerView.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage(bannerView, IMAGE_REQUEST_BANNER_CODE);
            }
        });

        bannerView.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                mBannerPicList.remove(pos);
            }
        });
    }

    private void setUpLogoView() {
        logoView.setAddHandlerImage(R.drawable.image_add);
        logoView.setImageSizeConfig(new MultiImageUploadView.ImageSizeConfig() {
            @Override
            public int getWidth() {
                return 200;
            }

            @Override
            public int getHeight() {
                return 200;
            }
        });
        logoView.setMax(1);
        logoView.setNumCol(4);
        logoView.setImgMargin(DisplayUtil.dp2px(this, 10));
        logoView.setCloseHandlerImage(R.drawable.ic_delete_photo);
        logoView.setOnItemClickListener(new MultiImageUploadView.OnItemClickListener() {
            @Override
            public void onItemClick(MultiImageUploadView parent, int position) {
                ArrayList<String> list=new ArrayList<>();
                list.add(parent.getFiles().get(position).getPath());
                Intent intent = new Intent(BaseInfoActivity.this, PictureViewerActivity.class);
                intent.putExtra("pic_all", list);
                intent.putExtra("pic_position",position);
                startActivity(intent);
            }
        });

        logoView.setPadding(0, 0, 0, 0);
        logoView.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage(logoView, IMAGE_REQUEST_lOGO_CODE);
            }
        });

        logoView.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                if (mLogoPicList.size() > 0) {
                    mLogoPicList.remove(pos);
                }

            }
        });
        //选择地址
        tvLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityChooseDialog.getInstance().showBottomSexDialog(BaseInfoActivity.this, provinceID + "", new CityChooseDialog.CitySelectListener() {

                    @Override
                    public void citySelectListener(String provinceName, String cityName, String areaName, String path) {
                        String[] list = path.split(",");
                        if (list.length == 5) {
                            mProvinceName = provinceName;
                            mProvinceID = list[2] + "";
                            mcityName = cityName;
                            mcityID = list[3] + "";
                            mAreaName = areaName;
                            mAreaid = list[4] + "";
                            currentarea = provinceName + cityName + areaName;
                            tvLocation.setText(currentarea);
                        } else {
                            mProvinceName = provinceName;
                            mProvinceID = list[2] + "";
                            mcityName = cityName;
                            mcityID = list[3] + "";
                            mAreaName = areaName;
                            mAreaid = "0";
                            currentarea = provinceName + cityName + areaName;
                            tvLocation.setText(currentarea);
                        }

                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String path = "";
        if (resultCode == RESULT_OK) {
            try {
                Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = BaseInfoActivity.this.getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                path = cursor.getString(columnIndex);  //获取照片路径

                //String compresspath = ImageUtil.compressImage(path);
                // sendPictureMessage(compresspath);

                cursor.close();
            } catch (Exception e) {
                // TODO Auto-generatedcatch block
                e.printStackTrace();
                return;
            }


            switch (requestCode) {
                case IMAGE_REQUEST_lOGO_CODE:
                    uploadPicture(path, IMAGE_REQUEST_lOGO_CODE);

                    break;
                case IMAGE_REQUEST_BANNER_CODE:
                    uploadPicture(path, IMAGE_REQUEST_BANNER_CODE);
                    break;

                case IMAGE_REQUEST_Jianjie_CODE:
                    uploadPicture(path, IMAGE_REQUEST_Jianjie_CODE);

                    break;
            }
        }
    }

    private void uploadPicture(String path, int code) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                compressImage(path, emitter);
            }
        }).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "onNext" + s);
                uploadImge(s, path, code);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    public void compressImage(String filePath, final ObservableEmitter<String> emitter) {
        File oldFile = new File(filePath);
        Log.d("图片压缩", "之前" + oldFile.length());
        Luban.with(BaseInfoActivity.this)
                .load(filePath)
                .ignoreBy(100)
                .setTargetDir(Environment.getExternalStorageDirectory().getAbsolutePath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {

                        Log.d("图片压缩", "之后" + file.length());
                        emitter.onNext(Base64Util.imageToBase64(file.getAbsolutePath()));


                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();

    }

    private void uploadImge(String s, final String path, final int code) {

        NetServices.Factory.getService().UploadImage(
                s + ""
                , "3"
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<UploadImageEntity>(BaseInfoActivity.this) {
                    @Override
                    protected void onSuccees(BaseEntity<UploadImageEntity> t) throws Exception {
                        Log.d(TAG, t.getData().toString());
                        if (code == IMAGE_REQUEST_lOGO_CODE) {
                            mLogoPicList.add(t.getData().getSavePath());
                            logoView.addFile(new File(path));
                        } else if (code == IMAGE_REQUEST_BANNER_CODE) {
                            mBannerPicList.add( t.getData().getSavePath());
                            bannerView.addFile(new File(path));
                        } else {
                            mJianjiePicList.add(t.getData().getSavePath());
                            jianjieView.addFile(new File(path));
                        }

                    }

                });

    }

    private void startSelectImage(RoundImageUploadView view, int requestcode) {
//        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        startActivityForResult(intent, IMAGE_REQUEST_CODE);

//        BoxingConfig mulitImgConfig = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG)
//                .needCamera(R.drawable.ic_camera)
//                .needGif()
//                .withMaxCount(view.getMax() - view.getFiles().size());
//        Boxing.of(mulitImgConfig).
//                withIntent(this, MyBoxingActivity.class).
//                start(this, requestcode);
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, requestcode);

    }

    @Override
    public boolean IsShowBackIcon() {
        return true;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
